// arch-tag: abdb0b07-2f4b-4fc1-b478-a27dbecda507
package de.yvert.jingle.impl.writer;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;

import de.yvert.jingle.Image;
import de.yvert.jingle.ImageType;
import de.yvert.jingle.ImageWriter;
import de.yvert.jingle.hdr.HdrImage2D;
import de.yvert.jingle.help.ConverterOutputStream;

/**
 * Simple HDR-format image writer. Currently only used
 * to export Shadow Maps to Yvert.
 * 
 * @author Stefan Goldmann, Ulf Ochsenfahrt
 */
public class ImageWriter_hdr implements ImageWriter
{

private static final int MAGIC = 0xABCDDCBA;
private static final int HEADERLENGTH = 4*4;

public ImageWriter_hdr()
{/*OK*/}

public String getExtension()
{ return "hdr"; }

public ImageType[] supportedTypes()
{ return new ImageType[] { ImageType.RGBA_2D_FLOAT }; }

public void write(Image in, OutputStream out) throws IOException
{
	HdrImage2D image = (HdrImage2D) in;
	
	// MUST be buffered, otherwise it will take ages to write the hdr data
	ConverterOutputStream cout = new ConverterOutputStream(ByteOrder.LITTLE_ENDIAN, new BufferedOutputStream(out));
	int width = image.getWidth();
	int height = image.getHeight();
	
	// Write header
	cout.writeInt(MAGIC);
	cout.writeInt(HEADERLENGTH+4*4*width*height);
	cout.writeInt(width);
	cout.writeInt(height);
	
	// Write data 
	for (int y = height-1; y >= 0; y--)
		for (int x = 0; x < width; x++)
		{
			cout.writeFloat(image.getRed(x,y));
			cout.writeFloat(image.getGreen(x,y));
			cout.writeFloat(image.getBlue(x,y));			
			cout.writeFloat(image.getAlpha(x,y));			
		}
	cout.flush();
}

}
